/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.bemanager.util;

import com.inspur.edp.jittojava.context.service.CommonService;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * 文件工具类
 *
 * @author haoxiaofei
 */
public class BefFileUtil {

    private static final String pomFile = "pom.xml";

    public static String getPomFilePath(String projectPath) {
        return projectPath + File.separator + pomFile;
    }

    public static String getAbsolutePathString(String path) {
        return new File(path).getAbsolutePath();
    }

    public static String getTagValue(Element ele, String tagName) {
        Element tagElement = (Element) ele.element(tagName);
        if (tagElement == null) {
            return null;
        }
        return tagElement.getText();
    }

    public static Document readDocument(String filePath) {
        SAXReader sr = new SAXReader();
        try {
            return sr.read(filePath);
        } catch (DocumentException e) {
            throw new RuntimeException("无效路径" + filePath);
        }
    }

    public static void saveDocument(Document document, File xmlFile) {
        Writer osWrite = null;// 创建输出流
        try {
            osWrite = new OutputStreamWriter(new FileOutputStream(xmlFile));

            OutputFormat format = OutputFormat.createPrettyPrint(); // 获取输出的指定格式
            format.setEncoding("UTF-8");// 设置编码 ，确保解析的xml为UTF-8格式
            XMLWriter writer = new XMLWriter(osWrite, format);// XMLWriter
            // 指定输出文件以及格式
            writer.write(document);// 把document写入xmlFile指定的文件(可以为被解析的文件或者新创建的文件)
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void log(String message) {
        Boolean showLog = true;
        if (showLog) {
            System.out.println(message);
        }
    }

    public static void excecuteCommand(Process process, String command, String funcMessage) {
        // 执行命令
        try {
            process = Runtime.getRuntime().exec(command);
            BefFileUtil.log(funcMessage + "开始...");
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                BefFileUtil.log(line);
            }
            process.waitFor();
            if (process.exitValue() == 1) {
                BefFileUtil.log(funcMessage + "失败");
            }
            BefFileUtil.log(funcMessage + "完成");
            process.destroy();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static String getJavaProjPath(String metaProjectPath) {
        return String.format("%1$s/%2$s", metaProjectPath,
            BefFileUtil.getService(CommonService.class).getProjectPath(metaProjectPath));
    }

    public static String getServerPath() {
        String runtimePath = System.getProperty("java.class.path");
        int endIndex = runtimePath.indexOf("/runtime");
        if (endIndex == -1) {
            endIndex = runtimePath.indexOf("\\runtime");
            if (endIndex == -1) {
                throw new RuntimeException(String.format("无法根据%1$s获取serverPath", runtimePath));
            }
        }
        String serverPath = runtimePath.substring(0, endIndex);
        return serverPath;
    }

    public static <T> T getService(Class<T> type) {
        return SpringBeanUtils.getBean(type);
    }
}
